# coding=utf8
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@stringfilter 
def truncatehanzi(value, arg):
    try:
        bits = []
        for x in arg.split(u':'):
            if len(x) == 0:
                bits.append(None)
            else:
                bits.append(int(x))
        if int(x) < len(value):
            return value[slice(*bits)] + '...'
        return value[slice(*bits)]
    except (ValueError, TypeError):
        return value

@stringfilter 
def truncatehanziwithoutdot(value, arg):
    try:
        bits = []
        for x in arg.split(u':'):
            if len(x) == 0:
                bits.append(None)
            else:
                bits.append(int(x))
        return value[slice(*bits)]
    except (ValueError, TypeError):
        return value

register.filter('truncatehanzi', truncatehanzi)
register.filter('truncatehanziwithoutdot', truncatehanziwithoutdot)
